package com.ccys.cms.controller.administrator;

import com.alibaba.excel.EasyExcel;
import com.ccys.cms.service.SysCodeService;
import com.ccys.cms.service.UserService;
import com.ccys.common.constants.ContextConstants;
import com.ccys.common.enums.CodeEnum;
import com.ccys.common.util.JedisUtil;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.administrator.ClinicSelectListDTO;
import com.ccys.db.dto.web.base.SysUserDto;
import com.ccys.db.entity.SysCode;
import com.ccys.db.entity.TblAccount;
import com.ccys.db.entity.TblCompany;
import com.ccys.db.vo.administrator.ClinicSelectListWebVO;
import com.ccys.db.vo.administrator.CompanySelectListWebVO;
import com.ccys.db.vo.administrator.PharmacySelectListWebVO;
import com.ccys.db.vo.web.base.AdminSelectVO;
import com.ccys.db.vo.web.base.AdminVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;

import java.util.List;

import static com.ccys.common.util.Kit.allParamValid;

/**
 * 管理员
 */
@Slf4j
@RestController
@RequestMapping("/administrator")
@Api(tags = "系统-子管理员模块")
public class AccountController {

    @Resource
    private UserService userService;

    @Resource
    private SysCodeService codeService;


    @GetMapping("/admin")
    @ApiOperation("查询子管理员")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "countryId", value = "国家ID",paramType = "query"),
        @ApiImplicitParam(name = "groupId", value = "集团ID",paramType = "query"),
        @ApiImplicitParam(name = "companyId", value = "companyId",paramType = "query"),
        @ApiImplicitParam(name = "clinicId", value = "clinicId",paramType = "query"),
        @ApiImplicitParam(name = "pharmacyId", value = "pharmacyId",paramType = "query"),
        @ApiImplicitParam(name = "roleIds", value = "角色ID",paramType = "query"),
        @ApiImplicitParam(name = "userStatus", value = "用户状态",paramType = "query"),
        @ApiImplicitParam(name = "userLoginStatus", value = "用户登录状态",paramType = "query"),
        @ApiImplicitParam(name = "startTime", value = "开始时间(格式 yyyy-mm-dd)", required = false, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "endTime", value = "结束时间(格式 yyyy-mm-dd)", required = false, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = "orderByStr", value = "排序字段（后端返回的字段  asc升序，desc 降序,加上end后缀。示例（createdOn降序排 则传值 createdOn descend））",paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = ContextConstants.MODEL_DESC,response = AdminVo.class)
    })
    public ResponseResult list( @ApiIgnore SysUserDto sysUserDto) {
        return userService.queryAdmins( sysUserDto);
    }


    @GetMapping("/admin/selectList")
    @ApiOperation("查询选择管理员")
    @ApiResponses({
        @ApiResponse(code = 200,message = ContextConstants.MODEL_DESC,response = AdminSelectVO.class)
    })
    public ResponseResult selectList( @ApiIgnore SysUserDto sysUserDto) {
        return userService.selectList( sysUserDto);
    }
    //clinic 下的下拉选择 使用诊所中的接口
    /*@ApiIgnore
    @GetMapping("/admin/clinicList")
    @ApiOperation("下拉clinic 列表选择")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "companyId", value = "公司ID",paramType = "query"),
        @ApiImplicitParam(name = "doctorId", value = "医生Id",paramType = "query"),
    })
    @ApiResponses({
        @ApiResponse(code = 200,message = ContextConstants.MODEL_DESC,response = ClinicSelectListWebVO.class)
    })
    public ResponseResult clinicList( @ApiIgnore ClinicSelectListDTO dto) {
        return userService.clinicSelectList(dto);
    }*/

    @GetMapping("/admin/pharmacyList")
    @ApiOperation("下拉pharmacy 列表选择")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "clinicId", value = "诊所ID",paramType = "query"),
        @ApiImplicitParam(name = "groupId", value = "集团ID",paramType = "query"),
    })
    @ApiResponses({
        @ApiResponse(code = 200,message = ContextConstants.MODEL_DESC,response = PharmacySelectListWebVO.class)
    })
    public ResponseResult pharmacyList( @ApiIgnore TblAccount dto) {
        UserUtil.getCurLoginUserId();
        return userService.pharmacySelectList( dto);
    }


    @GetMapping("/admin/companyList")
    @ApiOperation("下拉company 列表选择")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "groupId", value = "集团ID",paramType = "query"),
    })
    @ApiResponses({
        @ApiResponse(code = 200,message = ContextConstants.MODEL_DESC,response = CompanySelectListWebVO.class)
    })
    public ResponseResult companyList( @ApiIgnore TblAccount dto) {
        return userService.companySelectList( dto);
    }
    @PostMapping("/admin")
    @ApiOperation("新增子管理员")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "countryId", value = "国家ID 多个英文逗号分割",paramType = "query"),
        @ApiImplicitParam(name = "groupId", value = "groupId",paramType = "query"),
        @ApiImplicitParam(name = "companyId", value = "companyId",paramType = "query"),
        @ApiImplicitParam(name = "clinicId", value = "clinicId",paramType = "query"),
        @ApiImplicitParam(name = "pharmacyId", value = "pharmacyId",paramType = "query"),
        @ApiImplicitParam(name = "userName", value = "userName",paramType = "query"),
        @ApiImplicitParam(name = "userFullname", value = "userFullname",paramType = "query"),
        @ApiImplicitParam(name = "roleIds", value = "roleIds",paramType = "query"),
        @ApiImplicitParam(name = "userPassword", value = "userPassword",paramType = "query"),
        @ApiImplicitParam(name = "userEmail", value = "userEmail",paramType = "query"),
    })
    public ResponseResult insert(@ApiIgnore SysUserDto sysUserDto) {
        allParamValid(sysUserDto,"groupId","companyId","clinicId","pharmacyId",
                "userName","userFullname","roleIds","userPassword","userEmail");
        return userService.insertAdmin( sysUserDto);
    }

    @PutMapping("/admin")
    @ApiOperation("修改子管理员")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "countryId", value = "国家ID 多个英文逗号分割",paramType = "query"),
        @ApiImplicitParam(name = "id", value = "管理员id",paramType = "query"),
        @ApiImplicitParam(name = "groupId", value = "groupId",paramType = "query"),
        @ApiImplicitParam(name = "companyId", value = "companyId",paramType = "query"),
        @ApiImplicitParam(name = "clinicId", value = "clinicId",paramType = "query"),
        @ApiImplicitParam(name = "pharmacyId", value = "pharmacyId",paramType = "query"),
        @ApiImplicitParam(name = "userName", value = "userName",paramType = "query"),
        @ApiImplicitParam(name = "userFullname", value = "userFullname",paramType = "query"),
        @ApiImplicitParam(name = "roleIds", value = "roleIds",paramType = "query"),
        @ApiImplicitParam(name = "userPassword", value = "userPassword",paramType = "query"),
        @ApiImplicitParam(name = "userEmail", value = "userEmail",paramType = "query"),
        @ApiImplicitParam(name = "userStatus", value = "用户状态",paramType = "query"),
        @ApiImplicitParam(name = "userLoginStatus", value = "用户登录状态",paramType = "query"),
    })
    public ResponseResult update(@ApiIgnore SysUserDto sysUserDto) {
        allParamValid(sysUserDto,"id");
        if (sysUserDto.getUserStatus() != null && sysUserDto.getUserStatus() == 0) {
            if(JedisUtil.get(sysUserDto.getId(), CodeEnum.REDIS_USER.codeOf())!=null){
                JedisUtil.del(JedisUtil.get(sysUserDto.getId(), CodeEnum.REDIS_USER.codeOf()));
            }
            JedisUtil.del(sysUserDto.getId(), CodeEnum.REDIS_USER.codeOf());
        }
        return userService.updateAdmin( sysUserDto);
    }

    @DeleteMapping("/admin")
    @ApiOperation("删除子管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员id",paramType = "query"),
    })
    public ResponseResult delete(@ApiIgnore SysUserDto sysUserDto) {
        allParamValid(sysUserDto,"id");
        if(sysUserDto.getId().equals(UserUtil.getCurLoginUserId())) {
            return ResponseResult.error("Cannot delete oneself ！");
        }
        sysUserDto.setDelFlag(1);
        return userService.updateAdmin( sysUserDto);
    }

    @PutMapping("/admin/updatePwd")
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员id",paramType = "query",required = true),
            @ApiImplicitParam(name = "userPassword", value = "密码",paramType = "query",required = true),
    })
    public ResponseResult updatePwd(@ApiIgnore SysUserDto dto){
        if(StringUtil.isEmpty(dto.getId()) || StringUtil.isEmpty(dto.getUserPassword())) {
            return ResponseResult.error("parameter id or userPassword empty");
        }
        TblAccount user = new TblAccount();
        user.setId(dto.getId());
        user.setUserPassword(Kit.getPassword(dto.getUserPassword()));
        return ResponseResult.update(userService.updateEntityById(user));
    }

    @PutMapping("/admin/resetPwd")
    @ApiOperation("重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员id",paramType = "query",required = true),
    })
    public ResponseResult resetPwd(@ApiIgnore SysUserDto dto){
        Kit.allParamValid(dto,"id");
        TblAccount user = new TblAccount();
        user.setId(dto.getId());
        user.setUserPassword(Kit.getPassword(ContextConstants.DEFAULT_PWD));
        return ResponseResult.update(userService.updateEntityById(user));
    }

    @GetMapping("/test")
    public void test(){
        List<SysCode> list = EasyExcel.read("/Users/billyhu/Downloads/codes.xls").head(SysCode.class).sheet().doReadSync();
        list.forEach(c->{
            codeService.saveEntity(c);
        });
        System.out.println("完成");
    }
}
